#include <QApplication>
#include <QDebug>
#include <QDesktopServices>
#include <QUrl>

#include "defines.h"
#include "symbiandefines.h"
#include "generatoroutputview.h"
#include "infoplistparser.h"
#include "directoryutilities.h"
#include "fileutilities.h"
#include "configxmlparser.h"
#include "settings.h"
#include "hybridpluginxmlhandler.h"

#include "symbianqtprojectgenerator.h"
#include "symbianstatusupdater.h"
#include "symbianprocessrunner.h"
#include "symbiansettingsgui.h"


SymbianQtProjectGenerator::SymbianQtProjectGenerator(GeneratorOutputView & outputView,
                                                     QObject             * parent)
     : IQtProjectGenerator(parent),
       m_outputView(outputView),
       m_currentGeneratorPhase(INITIAL),
       m_generatorTarget(NO_TARGET),
       m_resolvedWidgetType(UNKNOWN_WIDGET)
{
    m_processRunner = new SymbianProcessRunner(*this);
}


SymbianQtProjectGenerator::~SymbianQtProjectGenerator()
{
    delete m_processRunner;
    m_processRunner = 0;
}


IStatusUpdater * SymbianQtProjectGenerator::createStatusUpdater(QObject * parent)
{
    IStatusUpdater
        * rv = new SymbianStatusUpdater(*this,
                                        parent);

    return rv;
}

const PlatformType& SymbianQtProjectGenerator::platform()
{
    m_platform.m_platformName = SYMBIAN_PLATFORMNAME;
    m_platform.m_platformVersion = 5; // This should be from settings by detecting the used SDK
    m_platform.m_qtVersion = Settings::get(Settings::QtVersion).toInt();

    return m_platform;
}

void SymbianQtProjectGenerator::build(const QString &widgetFile,
                                      RcSession     & /* rcSession */)
{
    emit started(BUILD);
    m_generatorTarget = BUILD;
    m_currentGeneratorPhase = INITIAL;
    m_resolvedWidgetType = UNKNOWN_WIDGET;
    if (!registerStatus(prepareEnvironment(widgetFile)))
            return;

    copyWidgetDirectory(widgetFile);
}


void SymbianQtProjectGenerator::rebuild(RcSession     & /* rcSession */)
{
    emit started(REBUILD);
    m_generatorTarget = REBUILD;
    m_currentGeneratorPhase = INITIAL;
    startBuild();
}


void SymbianQtProjectGenerator::preview(const QString &widgetFile)
{
    emit started(PREVIEW);
    m_generatorTarget = PREVIEW;
    m_currentGeneratorPhase = INITIAL;
    m_resolvedWidgetType = UNKNOWN_WIDGET;
    if (!registerStatus(prepareEnvironment(widgetFile)))
            return;

    copyWidgetDirectory(widgetFile);
}


void SymbianQtProjectGenerator::closeProject()
{
    m_generatorTarget = NO_TARGET;
    m_currentGeneratorPhase = INITIAL;
    m_resolvedWidgetType = UNKNOWN_WIDGET;
}


GeneratorOutputView & SymbianQtProjectGenerator::outputView() const
{
    return  m_outputView;
}


GeneratorData & SymbianQtProjectGenerator::generatorData()
{
    return m_generatorData;
}


GeneratorPhase SymbianQtProjectGenerator::getCurrentPhase() const
{
    return m_currentGeneratorPhase;
}


GeneratorTarget SymbianQtProjectGenerator::getTarget() const
{
    return m_generatorTarget;
}


QString SymbianQtProjectGenerator::getStatusText() const
{
    QString statusText;
    switch(m_currentGeneratorPhase.m_phase)
    {
    case UNZIP_WIDGET:
        statusText = HAG_STATUS_EXTRACTING_WIDGET;
        break;
    case QMAKE_APP:
    case MAKE_APP:
    case MAKESIS_APP:
        statusText = QString("Building %1").arg(m_generatorData.infoPlistValue(INFO_PLIST_KEY_DISPLAY_NAME));
        break;
    case INITIAL:
        statusText = HAG_STATUS_IDLE;
        break;
    case ENDED_SUCCESSFULLY:
        statusText = HAG_STATUS_COMPLETED_OK;
        break;
    case ENDED_WITH_ERRORS:
        statusText = HAG_STATUS_COMPLETED_NOTOK;
        break;
    }

    return statusText;
}

QWidget * SymbianQtProjectGenerator::createSettingsWidget(const QString & /* widgetFile */,
                                                          QWidget       * parent) const
{
    QWidget
        * rv = new SymbianSettingsGui(parent);

    return rv;
}


void SymbianQtProjectGenerator::saveSettings(QWidget * settingsWidget) const
{
    SymbianSettingsGui
        * symbianSettingsGui = dynamic_cast<SymbianSettingsGui*>(settingsWidget);

    if (symbianSettingsGui != NULL)
    {
        symbianSettingsGui->saveSettings();
    }
}


QStringList SymbianQtProjectGenerator::errorsForTarget(GeneratorTarget target) const
{
    QStringList errors;
    QString env = Settings::get(Settings::QtEnvBatPath).toString();

    // This is a hackish way to check that the qtenv.bat points to
    // a directory that contains Symbian capable Qt. This should be
    // replaced with a better method if one is found.
    if (!QFile::exists(env) || !QFile::exists(QFileInfo(env).absolutePath() + "/runonphone.exe"))
    {
        // No qtenv.bat
        if (target == BUILD)
        {
            errors.append("Valid path to qtenv.bat not found! Please specify in settings.");
        }
    }

    // Try to open the log file for writing
    QFile log(Settings::get(Settings::LogFilePath).toString());
    if (!log.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        // Failed to open the log file
        if (target != NO_TARGET)
        {
            errors.append("Failed to open log file for writing! Check settings.");
        }
    }
    log.close();

    // Return the requested validity setting
    return errors;
}


IQtProjectGenerator::PkgInstallResult
SymbianQtProjectGenerator::installPkg(const QFileInfo & pkgFile) const
{
    IQtProjectGenerator::PkgInstallResult
        rv = PKGINSTALL_ERROR;

    if (pkgFile.isFile() && pkgFile.exists())
    {
        QDesktopServices::openUrl(QUrl::fromLocalFile(pkgFile.canonicalFilePath()));
        rv = PKGINSTALL_OK;
    }

    return rv;
}


void SymbianQtProjectGenerator::qmakeFinished(int                  exitCode,
                                              QProcess::ExitStatus exitStatus)
{
    if (!exitCode && !exitStatus)
    {
        makeApplication();
    }
    else
    {
        registerStatus(false);
        QString msg = QString(ERR_PROCESS_FINISHED_WITH_ERRORS_CANNOT_CONTINUE).arg(QMAKE_APP_NAME) + QString(MSG_PROCESS_EXIT_CODE_STATUS).arg(exitCode).arg(exitStatus);
        m_outputView.printOutput(msg);
        emit finished(EXIT_FAILURE);
    }
}


void SymbianQtProjectGenerator::makeFinished(int                  exitCode,
                                             QProcess::ExitStatus exitStatus)
{
    if (!exitCode && !exitStatus && !m_processRunner->errorWordInLogMessage())
    {
        makeSisApplication();
    }
    else
    {
        registerStatus(false);
        QString msg = QString(ERR_PROCESS_FINISHED_WITH_ERRORS_CANNOT_CONTINUE).arg(MAKE_APP_NAME) + QString(MSG_PROCESS_EXIT_CODE_STATUS).arg(exitCode).arg(exitStatus);
        m_outputView.printOutput(msg);
        emit finished(EXIT_FAILURE);
    }
}


void SymbianQtProjectGenerator::makesisFinished(int                  exitCode,
                                                QProcess::ExitStatus exitStatus)
{
    if (!exitCode && !exitStatus)
    {
        m_currentGeneratorPhase = ENDED_SUCCESSFULLY;
        emit finished(EXIT_FAILURE);
    }
    else
    {
        registerStatus(false);
        QString msg = QString(ERR_PROCESS_FINISHED_WITH_ERRORS_CANNOT_CONTINUE).arg(MAKESIS_APP_NAME) + QString(MSG_PROCESS_EXIT_CODE_STATUS).arg(exitCode).arg(exitStatus);
        m_outputView.printOutput(msg);
        emit finished(EXIT_FAILURE);
    }
}


void SymbianQtProjectGenerator::widgetFilesCopied(int                  exitCode,
                                                  QProcess::ExitStatus exitStatus)
{
    if (!exitCode && !exitStatus)
    {
        if (m_generatorTarget == PREVIEW)
        {
            // Preview does not need any further steps
            // Signal finish(int) is emitted when the preview closes
            m_currentGeneratorPhase = ENDED_SUCCESSFULLY;
            startPreview();
        }
        else
        {
            // If not preview, continue building
            prepareProject();
        }
    }
    else
    {
        registerStatus(false);
        QString msg = QString(ERR_PROCESS_FINISHED_WITH_ERRORS_CANNOT_CONTINUE).arg(UNZIP_APP_NAME) + QString(MSG_PROCESS_EXIT_CODE_STATUS).arg(exitCode).arg(exitStatus);
        m_outputView.printOutput(msg);
        emit finished(EXIT_FAILURE);
    }
}



bool SymbianQtProjectGenerator::prepareEnvironment(const QString &widgetFile)
{
    // clear data structures
    m_generatorData.clearAll();
    m_generatorData.initPaths(widgetFile,
                              SYMBIAN_PLATFORMNAME);

    QString basePath = m_generatorData.basePath();
    QString buildDirectory = m_generatorData.buildDirectory();
    QString projectDirectory = m_generatorData.projectDirectory();
    QString widgetDirectory = m_generatorData.widgetDirectory();

    QDir dir;
    // Check the base directory, create if missing
    if (!dir.exists(basePath) && !dir.mkdir(basePath))
    {
        return false;
    }

    // Check the build directory, create if missing
    if (!dir.exists(buildDirectory) && !dir.mkdir(buildDirectory))
    {
        return false;
    }

    // Check the build directory, create if missing
    if (!dir.exists(projectDirectory) && !dir.mkdir(projectDirectory))
    {
        return false;
    }

    // Check the project directory
    if (!dir.exists(widgetDirectory))
    {
        if (!dir.mkdir(widgetDirectory))
        {
            return false;
        }
    }
    else
    {
        // Clean the project directory
        DirectoryUtilities::cleanDirectory(widgetDirectory, true, widgetDirectory);
    }

    return true;
}


bool SymbianQtProjectGenerator::prepareEnvironmentForNonWRTWidget()
{
    FileUtilities fileUtilities(m_outputView, m_generatorData);
    bool retval = false;

    if (m_resolvedWidgetType == OPERA_WIDGET || m_resolvedWidgetType == W3C_WIDGET)
    {
        retval = fileUtilities.configXmlToInfoPlistFile(m_resolvedWidgetType);
    }
    else if (m_resolvedWidgetType == DIRECTORY)
    {
        retval = fileUtilities.directoryToInfoPlistFile();
    }

    return retval;
}


void SymbianQtProjectGenerator::unzipWidgetFile(const QString &widgetFile)
{
    QFileInfo widgetFileInfo(widgetFile);
    if (widgetFileInfo.completeSuffix() == WRT_WIDGET_FILE_EXTENSION)
            m_resolvedWidgetType = WRT_WIDGET;

    QString unzipDir = m_generatorData.widgetDirectory();

    // Run unzip normally
    qDebug() << "Unzip";
    QStringList params;
    params << widgetFile << unzipDir;
    m_currentGeneratorPhase = UNZIP_WIDGET;
    m_processRunner->runApp(m_currentGeneratorPhase, params);
}


bool SymbianQtProjectGenerator::handleWidgetConfigFile()
{
    InfoPlistParser infoPlistParser(m_outputView, m_generatorData);
    return infoPlistParser.parse();
}


void SymbianQtProjectGenerator::handleWidgetDirectory()
{
    QDir widgetDir = m_generatorData.widgetDirectory();
    QDir::Filters filters = QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot;
    QStringList nameFilters;
    DirectoryUtilities dirUtil(m_outputView, m_generatorData);
    qDebug() << "DIR VERSION" << widgetDir;
    dirUtil.getFiles(widgetDir.canonicalPath(), filters, nameFilters, widgetDir.canonicalPath().length(), WIDGET_SUBDIR, m_generatorData.widgetSrcFiles());
    m_outputView.printOutput(QString(MSG_WIDGET_DIRECTORY_PROCESSED_N_FILES_FOUND).arg(m_generatorData.widgetSrcFiles().count()));
}


bool SymbianQtProjectGenerator::parsePluginsProjectFile()
{
    FileUtilities fileUtilities(m_outputView, m_generatorData);
    return fileUtilities.createPluginsProjectFile(plugins());
}


bool SymbianQtProjectGenerator::parseWidgetProjectFile()
{
    FileUtilities fileUtilities(m_outputView, m_generatorData);
    return fileUtilities.createWidgetProjectFile(plugins());
}


void SymbianQtProjectGenerator::parseWidgetResourceFile()
{
    FileUtilities fileUtilities(m_outputView, m_generatorData);
    fileUtilities.createWidgetResourceFile();
}


bool SymbianQtProjectGenerator::updateMainFile()
{
    FileUtilities fileUtilities(m_outputView, m_generatorData);
    return fileUtilities.updateMainFile();
}


bool SymbianQtProjectGenerator::updateMainWindowFile()
{
    FileUtilities fileUtilities(m_outputView, m_generatorData);
    return fileUtilities.updateMainWindowFile();
    }


bool SymbianQtProjectGenerator::copyHybridapiJs()
{
    QString sourceFileName(QApplication::applicationDirPath()+QString(TEMPLATES_DIR) + QString(HYBRIDAPI_JS_FILE));
    QString destinationFileName(m_generatorData.infoPlistValue(KEY_WIDGET_ROOT_DIR) + HYBRIDAPI_JS_FILE);

    QFileInfo sourceInfo(sourceFileName), destinationInfo(destinationFileName);

    if (!sourceInfo.exists())
    {
        QString errMsg = QString(ERR_FILE_NOT_FOUND).arg(HYBRIDAPI_JS_FILE);
        m_outputView.printOutput(errMsg);
        return false;
    }

    if (destinationInfo.exists())
    {
        QFile destinationFile(destinationFileName);
        destinationFile.remove();
    }

    QFile::copy(sourceFileName, destinationFileName);

    return true;
}


bool SymbianQtProjectGenerator::copyDisableSelectionCSS()
{
    QString sourceFileName(QApplication::applicationDirPath()+QString(TEMPLATES_DIR) + QString(DISABLE_SELECTION_CSS_FILE));
    QString destinationFileName(m_generatorData.infoPlistValue(KEY_WIDGET_ROOT_DIR) + DISABLE_SELECTION_CSS_FILE);

    QFileInfo sourceInfo(sourceFileName), destinationInfo(destinationFileName);

    if (!sourceInfo.exists())
    {
        QString errMsg = QString(ERR_FILE_NOT_FOUND).arg(DISABLE_SELECTION_CSS_FILE);
        m_outputView.printOutput(errMsg);
        return false;
    }

    if (destinationInfo.exists())
    {
        QFile destinationFile(destinationFileName);
        destinationFile.remove();
    }
    m_outputView.printOutput("Copy: " + sourceFileName + ", " + destinationFileName);
    QFile::copy(sourceFileName, destinationFileName);

    return true;
}


bool SymbianQtProjectGenerator::copyFrameworkAndPluginSrcFiles()
{
    DirectoryUtilities dirUtil(m_outputView, m_generatorData);

    // Copy the framework files
    qDebug() << QApplication::applicationDirPath() + FRAMEWORK_DIR << m_generatorData.fwDirectory();
    if (!dirUtil.copyDirectory(QApplication::applicationDirPath() + FRAMEWORK_DIR, m_generatorData.fwDirectory()))
        return false;

    // Copy the plugin stub files
    qDebug() << QApplication::applicationDirPath() + PLUGINSTUBS_DIR << m_generatorData.projectDirectory() + PLUGINSTUBS_DIR;
    if (!dirUtil.copyDirectory(QApplication::applicationDirPath() + PLUGINSTUBS_DIR, m_generatorData.projectDirectory() + PLUGINSTUBS_DIR))
        return false;

    // Copy the template files
    qDebug() << QApplication::applicationDirPath() + TEMPLATES_DIR << m_generatorData.projectDirectory();
    if (!dirUtil.copyDirectory(QApplication::applicationDirPath() + TEMPLATES_DIR, m_generatorData.projectDirectory()))
        return false;

    // Copy the plugins
    qDebug() << QApplication::applicationDirPath() + PLUGINS_DIR << m_generatorData.mwDirectory();
    if (!dirUtil.copyDirectory(QApplication::applicationDirPath() + PLUGINS_DIR, m_generatorData.mwDirectory()))
        return false;

    return true;
}


bool SymbianQtProjectGenerator::updateFrameworkProjectFile()
{
    FileUtilities fileUtilities(m_outputView, m_generatorData);
    QString fwProjectFile = m_generatorData.fwDirectory() + FRAMEWORK_PROJECT_FILE;
    qDebug() << "Updating fw project file: " << fwProjectFile;
    return fileUtilities.updateProjectFile(fwProjectFile);
}


void SymbianQtProjectGenerator::sniffWidgetType()
{
    // find config.xml
    QString w3cConfigFileName(m_generatorData.widgetDirectory() + W3C_CONFIG_FILE);
    if (QFile::exists(w3cConfigFileName))
    {
        // analyze config.xml
        QFile w3cConfigFileIn(w3cConfigFileName);
        if (!w3cConfigFileIn.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QString errMsg = QString(ERR_FILE_OPEN_READ_FAILED_CANNOT_CONTINUE).arg(w3cConfigFileName);
            m_outputView.printOutput(errMsg);
            m_resolvedWidgetType = UNKNOWN_WIDGET;
        }
        QTextStream streamIn(&w3cConfigFileIn);
        w3cConfigFileIn.close();

        ConfigXmlParser parser(m_outputView, m_generatorData);
        parser.parse();

        QMap<QString, QString> &configXmlData = m_generatorData.configXmlData();

        if (configXmlData.contains("widget.name:"))
        {
            m_resolvedWidgetType = W3C_WIDGET;
        }
        else if (configXmlData.contains("widget.widgetname:"))
        {
            m_resolvedWidgetType = OPERA_WIDGET;
        }
    }
}


bool SymbianQtProjectGenerator::registerStatus(bool status)
{
    if (!status)
        m_currentGeneratorPhase = ENDED_WITH_ERRORS;

    return status;
}


bool SymbianQtProjectGenerator::embedFrameworkSis()
{
    // find name of sis file and UID3 of the framework
    QString uid3("");
    QString sisFileName("");
    QString mmpFileName("");
    QString pkgFileName("");
    QString frameworkDir = m_generatorData.fwDirectory();
    DirectoryUtilities dirUtil(m_outputView, m_generatorData);
    QStringList nameFilters;
    QDir::Filters filters = QDir::Files;

    nameFilters << "*.mmp";

    if (!dirUtil.getFile(frameworkDir, filters, nameFilters, mmpFileName))
    {
        QString errMsg = QString(ERR_FILE_NOT_FOUND_CAN_CONTINUE).arg("mmp-file in fw-directory");
        m_outputView.printOutput(errMsg);
        return true;
    }

    QFile mmpFile(mmpFileName);
    if (!mmpFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QString errMsg = QString(ERR_FILE_NOT_FOUND_CAN_CONTINUE).arg(mmpFileName);
        m_outputView.printOutput(errMsg);
        return true;
    }

    QTextStream stream(&mmpFile);
    QString fileLine;
    while(!stream.atEnd())
    {
        fileLine = stream.readLine();
        if (fileLine.trimmed().mid(0,4) == "UID " || fileLine.trimmed().mid(0,4) == "UID\t") {
            QStringList list;
            list = fileLine.split(QRegExp("\\s+"));
            if (list.count() != 3)
            {
                //something wrong
                QString errMsg = QString(ERR_CANNOT_FIND_UID3_IN_MMP_FILE).arg(mmpFileName);
                m_outputView.printOutput(errMsg);
                return true;
            }
            else
            {
                uid3 = list.at(2);
            }
            break;
        }
    }
    mmpFile.close();

    nameFilters.clear();
    nameFilters << "*.sis*";

    if (!dirUtil.getFile(frameworkDir, filters, nameFilters, sisFileName))
    {
        QString errMsg = QString(ERR_FILE_NOT_FOUND_CAN_CONTINUE).arg("sis-file");
        m_outputView.printOutput(errMsg);
        return true;
    }
    sisFileName = sisFileName.mid(frameworkDir.length());

    // find pkg-file and append to the end the following: @"embedded_sis.sisx", (embedded_sis_uid)
    QString embedSisCommand = QString("\n@\"fw/%1\", (%2)").arg(sisFileName).arg(uid3);

    QString pkgFileDir = m_generatorData.projectDirectory();
    nameFilters.clear();
    nameFilters << "*.pkg";

    if (!dirUtil.getFile(pkgFileDir, filters, nameFilters, pkgFileName))
    {
        QString errMsg = QString(ERR_FILE_NOT_FOUND_CAN_CONTINUE).arg(QString("pkg-file in ")+pkgFileDir);
        m_outputView.printOutput(errMsg);
        return true;
    }

    // do the embedding
    QFile pkgFileObject(pkgFileName);
    if (pkgFileObject.open(QIODevice::Append | QIODevice::Text))
    {
        QTextStream stream(&pkgFileObject);
        stream << embedSisCommand;
        pkgFileObject.close();
    }
    else
    {
        QString errMsg = QString(ERR_FILE_OPEN_WRITE_FAILED_CAN_CONTINUE).arg(pkgFileName);
        m_outputView.printOutput(errMsg);
    }

    return true;
}


void SymbianQtProjectGenerator::startBuild()
{
    QStringList params;
    m_currentGeneratorPhase = QMAKE_APP;
    m_processRunner->runApp(m_currentGeneratorPhase, params);
}


void SymbianQtProjectGenerator::startPreview()
{
    // copy framework and plugin source files to the build directory
    if (!registerStatus(copyFrameworkAndPluginSrcFiles()))
        return;

    // find out type of widget package
    sniffWidgetType();
    if (!registerStatus(m_resolvedWidgetType != UNKNOWN_WIDGET))
    {
        return;
    }

    if (m_resolvedWidgetType != WRT_WIDGET)
    {
        // create info.plist and copy widget files to right place
        if (!registerStatus(prepareEnvironmentForNonWRTWidget()))
            return;
    }

    // read in info.plist
    if (!registerStatus(handleWidgetConfigFile()))
        return;

    if (!registerStatus(copyHybridapiJs()))
        return;

    if (!Settings::get(Settings::TextSelectionEnabled).toBool())
    {
        if (!registerStatus(copyDisableSelectionCSS()))
        {
            return;
        }
    }

    // read in info of widget directory
    handleWidgetDirectory();

    FileUtilities fileUtilities(m_outputView, m_generatorData);
    qDebug() << "Identifier" << fileUtilities.getWidgetIdentifier();
    qDebug() << "Main file" << fileUtilities.getMainHTMLFileFullPath();

    QString launcher = "launcher.exe";
    QStringList arguments;
    arguments << fileUtilities.getWidgetIdentifier()
                    << fileUtilities.getMainHTMLFileFullPath()
                    << (Settings::get(Settings::PanningEnabled).toBool() ? "true" : "false");
    QProcess *process = new QProcess(this);
    connect(process, SIGNAL(finished(int)), this, SIGNAL(finished(int)));
    process->start(launcher, arguments);
}



void SymbianQtProjectGenerator::copyWidgetDirectory(const QString &filename)
{
    QFileInfo targetInfo(filename);
    if (!targetInfo.isDir())
    {
        // Not a directory, so proceed with unzip instead
        unzipWidgetFile(filename);
    }
    else
    {
        // Directory -- copy files directly
        qDebug() << "Copy directory";
        m_resolvedWidgetType = DIRECTORY;
        DirectoryUtilities dirUtil(m_outputView, m_generatorData);
        QString dest = m_generatorData.widgetDirectory();
        if (dirUtil.copyDirectory(filename, dest))
                widgetFilesCopied(0);
        else
                return;
    }
}


bool SymbianQtProjectGenerator::prepareProject()
{
    // copy framework and plugin source files to the build directory
    if (!registerStatus(copyFrameworkAndPluginSrcFiles()))
        return false;

    // find out type of widget package
    sniffWidgetType();
    if (!registerStatus(m_resolvedWidgetType != UNKNOWN_WIDGET))
    {
        return false;
    }

    if (m_resolvedWidgetType != WRT_WIDGET)
    {
        // create info.plist and copy widget files to right place
        if (!registerStatus(prepareEnvironmentForNonWRTWidget()))
            return false;
    }

    // read in info.plist
    if (!registerStatus(handleWidgetConfigFile()))
        return false;

    if (!registerStatus(copyHybridapiJs()))
        return false;

    if (!Settings::get(Settings::TextSelectionEnabled).toBool())
    {
        if (!registerStatus(copyDisableSelectionCSS()))
        {
            return false;
        }
    }

    // read in info of widget directory
    handleWidgetDirectory();

    // update main.cpp file
    if (!registerStatus(updateMainFile()))
        return false;

    // update mainwindow.cpp file
    if (!registerStatus(updateMainWindowFile()))
        return false;

    // generate Qt resource file
    parseWidgetResourceFile();

    // generate Qt project file
    if (!registerStatus(parseWidgetProjectFile()))
        return false;

    // Update the framework project file
    if (!registerStatus(updateFrameworkProjectFile()))
        return false;

    // Create mw.pro file that ties the plugins to the project,
    // also updates the plugin project files to e.g. include correct
    // Qt Mobility paths.
    if (!registerStatus(parsePluginsProjectFile()))
        return false;

    startBuild();

    return true;
}

void SymbianQtProjectGenerator::qmakeApplication()
{
    QStringList params;
    m_currentGeneratorPhase = QMAKE_APP;
    m_processRunner->runApp(m_currentGeneratorPhase, params);
}


void SymbianQtProjectGenerator::makeApplication()
{
    QStringList params;
    m_currentGeneratorPhase = MAKE_APP;
    m_processRunner->runApp(m_currentGeneratorPhase, params);
}


void SymbianQtProjectGenerator::makeSisApplication()
{
    // before makesis edit .pkg file to embed hybridfw.sis
    embedFrameworkSis();
    QStringList params;
    m_currentGeneratorPhase = MAKESIS_APP;
    m_processRunner->runApp(m_currentGeneratorPhase, params);
}


